package com.egdigital.allzic.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserLocation;
import com.egdigital.allzic.data.json.JsonParserStation;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Location;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.service.ServiceStreaming;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.GPSManager;
import com.egdigital.allzic.utils.NetworkManager;

public class FragmentExploreAround extends BaseMainFragment implements OnClickListener, OnItemClickListener, OnItemSelectedListener {

	private static final String		TAG						= FragmentExploreAround.class.getSimpleName();
	private Spinner					mSpinner;
	private AdapterListRadio		mAdapter;
	private LoadMoreListView		mListView;
	private ImageButton				mcloseButton;
	private TextView				mTitle;
	//
	private static final String		URL_GEO_NAMES			= "http://api.geonames.org/findNearbyPostalCodesJSON?lat=%s&lng=%s&username=egdigital";
	private static final int		SELECTION_CITY			= 0;
	private static final int		SELECTION_DEPARTMENT	= 1;
	private static final int		SELECTION_COUNTRY		= 2;
	private List<Station>			mList;
	private JsonParserStation		mJsonParserStation;
	private JsonParserLocation		mJsonParserLocation;
	private int						mSelectedCategory		= -1;
	private int						mCurrentPage			= 0;
	// network ui
	protected ActivityMain			mParent;
	protected View					mView;
	final public BroadcastReceiver	mPlayBackReceiver		= new BroadcastReceiver() {

																@Override
																public void onReceive(Context context, Intent intent) {
																	String actionString = intent.getAction();
																	if (actionString == ServiceStreaming.SERVICE_PLAY) {
																	} else if (actionString == ServiceStreaming.SERVICE_STOP) {
																	} else if (actionString == ServiceStreaming.SERVICE_LOADING) {
																	} else if (actionString == ServiceStreaming.SERVICE_ERROR) {
																	} else if (actionString == ServiceStreaming.SERVICE_KILLED) {
																	}
																}
															};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// player receivers
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_PLAY));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_STOP));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_LOADING));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_ERROR));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_KILLED));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_explore_around, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_around_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_around_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_around_noresult);
		//
		mListView = (LoadMoreListView) mView.findViewById(R.id.fragment_explore_around_list);
		mSpinner = (Spinner) mView.findViewById(R.id.fragment_explore_around_top_spinner);
		mcloseButton = (ImageButton) mView.findViewById(R.id.fragment_around_radio_close);
		mTitle = (TextView) mView.findViewById(R.id.fragment_explore_around_top_title);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// hack for click behind the fragment
		mView.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
		// listener
		mListView.setOnItemClickListener(this);
		mcloseButton.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		// title
		mTitle.setText(getString(R.string.fragment_explore_around));
		// spinner
		List<String> list = new ArrayList<String>();
		list.add("Ville");
		list.add("Dˇpartement");
		list.add("Pays");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mParent.getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(R.layout.view_drop_down);
		mSpinner.setAdapter(dataAdapter);
		mSpinner.setOnItemSelectedListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		// Analytics
		analyticsSendEvent("Around");
		VolleyManager.init(mParent);
		mJsonParserStation = new JsonParserStation();
		mJsonParserLocation = JsonParserLocation.getInstance();
		if (mList == null || mList.isEmpty()) {
			mJsonParserStation.initAndStartRequestQueue();
			mJsonParserLocation.initAndStartRequestQueue();
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.fragment_around_reload:
				loadData();
				break;
			case R.id.fragment_around_radio_close:
				mParent.removeFragment();
				break;
		}
	}

	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if (mParent != null) {
			Station station = mList.get(position);
			mParent.prepareToPlay(station);
			mParent.showPlayerBanner();
			mParent.updatePlayerBanner();
		}
	}

	/**
	 * animation
	 */
	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		Animation animation = super.onCreateAnimation(transit, enter, nextAnim);
		if (animation == null && nextAnim != 0) {
			animation = AnimationUtils.loadAnimation(getActivity(), nextAnim);
		}
		if (animation != null) {
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation animation) {
					getView().post(new Runnable() {

						@Override
						public void run() {
							loadData();
						}
					});
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animation;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		if (mJsonParserLocation != null) {
			mJsonParserLocation.stopRequestQueue();
		}
		if (mJsonParserStation != null) {
			mJsonParserStation.stopRequestQueue();
		}
		mParent.mExplorerSelected = false;
		mParent = null;
		super.onDetach();
	}

	@Override
	public void onDestroy() {
		if (mPlayBackReceiver != null) {
			LocalBroadcastManager.getInstance(mParent).unregisterReceiver(mPlayBackReceiver);
		}
		super.onDestroy();
	}

	private void loadData() {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			setCallBacks();
			startGeolocalisation();
		} else {
			setReload(mListView);
		}
	}

	private void startGeolocalisation() {
		GPSManager manager = GPSManager.getInstance();
		android.location.Location location = manager.getLocation(mParent.getApplicationContext());
		if (location != null) {
			String url = String.format(URL_GEO_NAMES, location.getLatitude(), location.getLongitude());
			mJsonParserLocation.extractJsonObjectData(url);
		}
	}

	private void setCallBacks() {
		mJsonParserStation = new JsonParserStation();
		mJsonParserStation.setJsonCallBack(new JsonCallBack() {

			@Override
			public void downloadStarted() {
				if (mCurrentPage == 0) {
					setLoading(mListView);
				}
			}

			@Override
			public void downloadPercent(int percent) {
				// do nothing
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				setReload(mListView);
			}

			/**
			 * Will display all station in the list
			 */
			@Override
			public <T> void downloadCompleted(List<T> list) {
				Log.i(TAG, "downloadCompleted station");
				if (mParent == null || list == null) {
					return;
				}
				if (!list.isEmpty()) {
					if (mList != null)
						mList.addAll((List<Station>) list);
					else
						mList = (List<Station>) list;
					updateAdapter(mList);
					setLoaded(mListView);
				} else {
					Log.i(TAG, "no result");
					// no result maybe
				}
				mListView.onLoadMoreComplete();
			}
		});
		/**
		 * Callback used by Volley when the download and parsing of places around the given lat and lng is done
		 */
		mJsonParserLocation = JsonParserLocation.getInstance();
		mJsonParserLocation.setJsonCallBack(new JsonCallBack() {

			@Override
			public void downloadStarted() {
				setLoading(mListView);
			}

			@Override
			public void downloadPercent(int percent) {
				// do nothing
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				setReload(mListView);
			}

			/**
			 * Will start the download and the parsing of stations depending of the user choice and place
			 */
			@Override
			public <T> void downloadCompleted(List<T> list) {
				try {
					switch (mSelectedCategory) {
						case SELECTION_CITY:
							String builder = "";
							for (int i = 0; i < list.size(); i++) {
								builder += ((com.egdigital.allzic.data.object.Location) list.get(i)).getCity();
								if (i < list.size() - 1)
									builder += "-";
							}
							mJsonParserStation.extractJsonObjectData(getString(R.string.url_around_zip) + ((Location) list.get(0)).getCountry() + "/" + builder + "/" + mCurrentPage);
							break;
						case SELECTION_DEPARTMENT:
							mJsonParserStation.extractJsonObjectData(getString(R.string.url_around_dept) + ((Location) list.get(0)).getCountry() + "/"
									+ ((com.egdigital.allzic.data.object.Location) list.get(0)).getDepartment() + "/" + mCurrentPage);
							break;
						case SELECTION_COUNTRY:
							mJsonParserStation.extractJsonObjectData(getString(R.string.url_around_country) + ((Location) list.get(0)).getCountry() + "/" + 1);
							break;
					}
				} catch (Exception e) {
					Log.e(TAG, "", e);
				}
			}
		});
		mListView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				mCurrentPage++;
				startGeolocalisation();
			}
		});
	}

	private void updateAdapter(List<Station> list) {
		if (mAdapter == null) {
			mAdapter = new AdapterListRadio(mParent.getApplicationContext(), list, R.layout.cell_list_radio);
			mListView.setAdapter(mAdapter);
			mListView.setSelection(0);
		} else {
			mAdapter.setData(list);
			mAdapter.notifyDataSetChanged();
		}
		mListView.setVisibility(View.VISIBLE);
		mListView.setOnItemClickListener(this);
	}

	@Override
	public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
		mCurrentPage = 0;
		mList = null;
		mListView.setSelection(0);
		if (mSelectedCategory != -1) {
			loadData();
		}
		mSelectedCategory = position;
	}

	@Override
	public void onNothingSelected(AdapterView<?> adapterView) {
		// do nothing
	}
}
